/*
 * ECARX Technology Limited is the owner of the copyright and the trade secret of this software.
 * Without permission, no one has the right to obtain, disclose or use this software in any way.
 */
package com.ecarx.systemui.plugin.ui.navigationbar

import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.core.content.res.ResourcesCompat
import com.ecarx.systemui.plugin.PluginContext
import com.ecarx.systemui.plugin.R
import com.ecarx.systemui.plugin.controller.CarVoiceController
import com.ecarx.systemui.plugin.controller.CarVoiceController.IOnVolumeChanged
import com.ecarx.systemui.plugin.ui.custom.SystemBarButton
import com.ecarx.systemui.plugin.ui.dialog.base.DialogManager
import com.ecarx.systemui.plugin.utils.LogUtils

class VolumeButton @JvmOverloads constructor(
    context: Context?,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : SystemBarButton(context, attrs, defStyleAttr) {

    private lateinit var carVoiceController : CarVoiceController
    init {
        showInitStatus()
        setOnClickListener { v: View? ->
            LogUtils.i("VolumeButton ----> clicked ~")
            DialogManager.getDialogManager().showGlobalVolumeDialog(PluginContext.getInstance().pluginContext, true)
        }
    }

    private fun showInitStatus() {
        carVoiceController = CarVoiceController.getCarVoiceController()
        carVoiceController.setOnVolumeChanged(object : IOnVolumeChanged {
            override fun onGroupMuteChanged() {
                LogUtils.d("VolumeButton", "showInitStatus onGroupMuteChanged")
                showVolume()
            }
            override fun onGroupVolumeChanged() {
                LogUtils.d("VolumeButton", "showInitStatus onGroupVolumeChanged")
                showVolume()
            }
        })
        showVolume()
    }

    private fun showVolume() {
        var isMute: Boolean = carVoiceController.isStreamMuteAll
        if (isMute) {

            setImageDrawable(
                ResourcesCompat
                    .getDrawable(resources, R.drawable.dock_bar_volume_mute_normal, context.theme)
            )
        } else {
            setImageDrawable(
                ResourcesCompat
                    .getDrawable(resources, R.drawable.dock_bar_volume_normal, context.theme)
            )
        }
    }

    override fun getContentDescriptionString(): String {
        return "VolumeButton"
    }
}